<template>
<!--
  is_ext_supplier 是否是外部资源订单。
    - 外部资源订单没有订单总码
    - 外部资源未出票的情况下，code 为空

  voucher_kind 核销码类型
    一单一码 0：有子码，但不一定有套餐总码
    一人一码 1：只有套餐总码，没有子码
-->
<div id="app" :class="{'fixed-warp-body': !isFromShare}">
  <nav-bar title="核销码" left-arrow @clickLeft="$goPageBack('order/list')" />
  <div v-if="data">
    <div class="panel-box mg-all">
      <div class="panel-head">
        {{firstProd.product_name}}
      </div>
      <div class="panel-body" v-if="!!mainVoucher.code">
        <voucher-img-block :data="mainVoucher" codeDesc="总核销码" />
      </div>
    </div>

    <div v-for="prod in data.items" :key="prod.code">
      <div class="panel-box mg-all" v-for="sku in prod.sku_codes" :key="prod.code + sku.code">
        <div class="panel-head">
          {{sku.sku_name}}
        </div>

        <collapse-panel :isCollapsed="sku.child_code && sku.child_code.length > 3">
          <template slot="panel">
            <ul class="panel-list mg-btm-sm">
              <li>
                <van-row>
                  <van-col class="c-gray-l" span="24">有效期：{{sku.avail_description}}</van-col>
                </van-row>
              </li>
              <li v-if="sku.code">
                <van-row>
                  <van-col span="23">
                    <span class="c-gray-l">套餐核销码：</span>
                    <a @click="showSheet(sku)">
                      <van-icon class-prefix="ucai-icon" name="ico" />
                    </a>
                    {{sku.code}}
                    <span :class="['pd-lft', getStatusClass(sku.state)]">{{sku.state_name}}</span>
                  </van-col>
                  <van-col class="text-right c-gray-l" span="1">
                    <a @click="goSingelPage(sku)">
                      <van-icon class-prefix="ucai-icon" name="arrow_rgt" />
                    </a>
                  </van-col>
                </van-row>
              </li>
              <li v-if="sku.verify_way == 0">
                <span class="c-warn">需整批入园，核销过一次后，不可再次核销</span>
              </li>
            </ul>
            <!-- BLOCK: 出行人 -->
            <ul class="panel-list" v-if="sku.child_code && sku.child_code.length > 1">
              <li class="table-head">
                <van-row>
                  <van-col span="17">子核销码</van-col>
                  <van-col span="7">对应出行人</van-col>
                </van-row>
              </li>
              <li v-for="traveler in sku.child_code" :key="traveler.identity_code+traveler.code">
                <van-row>
                  <van-col span="17">
                    <a @click="showSheet(sku, traveler)">
                      <van-icon class-prefix="ucai-icon" name="ico" />
                    </a>
                    {{traveler.code}}
                    <span :class="['pd-lft', getStatusClass(traveler.state)]">{{traveler.state_name}}</span>
                  </van-col>
                  <van-col span="6">{{traveler.name}}</van-col>
                  <van-col class="text-right c-gray-l" span="1">
                    <a @click="goSingelPage(traveler)">
                      <van-icon class-prefix="ucai-icon" name="arrow_rgt" />
                    </a>
                  </van-col>
                </van-row>
              </li>
            </ul>
          </template>
          <template slot="open-handler">
            <div class="panel-foot text-center c-main">
              展开子核销码
              <van-icon class-prefix="ucai-icon" name="arrow_rgt" />
            </div>
          </template>
        </collapse-panel>
      </div>
    </div>

    <!-- BLOCK: 按钮组 -->
    <div class="fixed-warp" v-if="!isFromShare">
      <div class="btn-group">
        <van-button
          size="small"
          type="default"
          plain
          hairline
          @click="$goPage('voucher/record', { order_no: order_no })"
        >核销明细</van-button>
        <van-button size="small" type="primary" @click="$refs['share-overlay'].isShow = true">分享</van-button>
      </div>
    </div>

    <!-- 水印 -->
    <slogan class="mg-top-xxl" />

    <!-- BLOCK: 弹窗-核销码明细 -->
    <van-action-sheet v-model="isShowVoucherSheet" title="核销码">
      <voucher-info-panel :data=sheetData />
    </van-action-sheet>

    <!-- BLOCK: 弹窗-分享 -->
    <share-overlay v-if="!isFromShare" ref="share-overlay" />
  </div>
  <no-data :text="errMsg" v-else-if="!isOnLoading" />
</div>
</template>

<script>
import {
  Icon,
  Button,
  Row,
  Col,
  ActionSheet,
  Toast,
} from 'vant'
import NavBar from "@cmpt/header/navbar"
import VoucherImgBlock from "@cmpt/voucher/img-block"
import VoucherInfoPanel from "@cmpt/voucher/info-panel"
import CollapsePanel from "@cmpt/panel/collapse"
import ShareOverlay from "@cmpt/share"
import TravelerItem from '@views/order/components/traveler-item'
import NoData from '@cmpt/no-data'
import Slogan from '@cmpt/slogan'

import {
  getOrderVoucher,
} from "@api/modules/order"
import {
  getErrInfo,
} from "@api/http"

import {
  VOUCHER_STATE_LIST
} from '@data/dic/order'

export default {
  name: 'voucher',
  components: {
    [Icon.name]: Icon,
    [Button.name]: Button,
    [Row.name]: Row,
    [Col.name]: Col,
    [ActionSheet.name]: ActionSheet,

    NavBar,
    VoucherImgBlock,
    VoucherInfoPanel,
    CollapsePanel,
    ShareOverlay,
    TravelerItem,
    NoData,
    Slogan,
  },

  data() {
    return {
      order_no: this.$getUrlParam('order_no') || '',
      is_encode: this.$getUrlParam('is_encode') || 0, // 是否加密 0:否 1:是
      data: null,
      errMsg: '',
      isOnLoading: false,
      // 核销码弹窗
      isShowVoucherSheet: false,
      sheetData: null,
    }
  },

  computed: {
    isFromShare: function () { // 是否来自分享，等价于 is_encode == 1
      // const data = this.data || {}
      // return data.from_share == 1
      return this.is_encode == 1
    },
    firstProd: function () { // 第一个产品数据
      const data = this.data || {}
      const list = data.items || []
      return list[0] || {}
    },
    mainVoucher: function () { // 总核销码
      const data = this.data || {}
      return {
        code: data.code,
        state: data.state,
        state_name: data.state_name,
      }
    }
  },

  methods: {
    async getData() {
      this.isOnLoading = true
      Toast.loading({
        duration: 10000,
        forbidClick: true
      })
      getOrderVoucher({
        order_no: this.order_no,
        is_encode: this.is_encode,
      }).then(res => {
        this.isOnLoading = false
        Toast.clear()
        this.data = res.data

        if (this.data.encode_order_no && !this.isFromShare) {
          this.$mergePageParams({
            order_no: this.data.encode_order_no,
            is_encode: 1,
          })
        }

        // 设置微信、app分享
        this.$set_share({
          title: `优采订单【${this.data.code}】`,
          desc: `${this.data.order_no}，${this.firstProd.product_name}`,
        })
      }).catch(err => {
        this.data = null
        const {
          msg
        } = getErrInfo(err)
        this.errMsg = msg
        this.isOnLoading = false
      })
    },

    /** 
     * 获取核销码状态颜色
     */
    getStatusClass(status) {
      const obj = VOUCHER_STATE_LIST.find((item) => {
        return item.key == status
      })
      return obj ? 'c-' + obj.styleType : ''
    },

    /** 
     * 展示出行人弹窗
     */
    showSheet(sku, traveler) {
      const voucherData = traveler || sku
      this.sheetData = {
        sku_name: sku.sku_name,
        avail_description: sku.avail_description,
        voucher: {
          code: voucherData.code,
          state: voucherData.state,
          state_name: voucherData.state_name,
          qr_code_url: voucherData.qr_code_url,
        },
        voucherCodeDesc: traveler ? '子核销码' : '套餐核销码',
        traveler: sku.has_traveler ? (traveler ? [traveler] : sku.child_code) : null,
      }
      this.isShowVoucherSheet = true
    },

    /** 
     * 跳转到单张核销码页面
     */
    goSingelPage(data) {
      this.$goPage('voucher/single', {
        order_no: this.order_no,
        code: this.isFromShare ? data.encode_code : data.code,
        is_encode: this.isFromShare ? 1 : 0
      })
    },

    resetPageUrl() {
      if (!this.isFromShare) {
        this.$mergePageParams({
          order_no: this.order_no,
          is_encode: 0,
        })
      }
    }
  },

  created() {
    this.getData()
    window.onbeforeunload = () => {
      this.resetPageUrl()
    }
  },
}
</script>

<style lang="less" src="@style_m/components/panel.less"></style>
<style lang="less" src="@style_m/mod/order-detail.less"></style><style lang="less" scoped>
@import "~@style_m/basic/utils/index";

.table-head {
  background: @color-bg-light;
}
</style>
